/*
 * node.c -- this file is part of mISPL.
 * Copyright (C) 2011 Christian Krause
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "node.h"

node_t node_init(int maxsize) {
	node_t node = malloc(sizeof(__node_s));
	node->size = 0;
	node->maxsize = maxsize;
	node->children = malloc(sizeof(node_t) * maxsize);
	node->values = malloc(sizeof(mpz_t) * maxsize);
	node->periods = malloc(sizeof(bool_t) * maxsize);
	return node;
}

void node_clear(node_t node) {
	int i;
	for (i=0; i<node->size; i++) {
		mpz_clear(node->values[i]);
	}
	free(node->values);
	free(node->children);
	free(node->periods);
	free(node);
}

void node_clear_all(node_t node) {
	int i;
	for (i=0; i<node->size; i++) {
		node_clear_all(&node->children[i]);
	}
	node_clear(node);
}

void node_grow(node_t node) {
	int i;
	node_t bigger = node_init(node->maxsize * 2);
	bigger->size = node->size;
	for (i=0; i<node->size; i++) {
		bigger->children[i] = node->children[i];
		bigger->values[i][0] = node->values[i][0];
		bigger->periods[i] = node->periods[i];
	}
	free(node->children);
	free(node->values);
	free(node->periods);
	node->children = bigger->children;
	node->values = bigger->values;
	node->periods = bigger->periods;
	free(bigger);
}

node_t node_get_child(node_t parent, mpz_t value, bool_t period) {
	int i;
	for (i=0; i<parent->size; i++) {
		if ((period==parent->periods[i]) && (mpz_cmp(parent->values[i], value)==0)) {
			return &parent->children[i];
		}
	}
	return NULL;
}

node_t node_add_child(node_t parent, mpz_t value, bool_t period) {
	node_t child = node_get_child(parent, value, period);
	if (child==NULL) {
		if (parent->size>=parent->maxsize) {
			node_grow(parent);
		}
		child = node_init(NODE_INIT_MAXSIZE);
		parent->children[parent->size] = *child;
		parent->periods[parent->size] = period;
		mpz_init_set(parent->values[parent->size], value);
		parent->size++;
	}
	return child;
}

node_t node_add_sequence(node_t parent, sequence_t sequence) {
	int i;
	bool_t period;
	node_t node = parent;
	for (i=0; i<sequence->length; i++) {
		period = (i==sequence->period) ? TRUE : FALSE;
		node = node_add_child(node, sequence->values[i], period);
	}
	return node;
}
